package com.huixh.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huixh.train.business.domain.DailyTrainCarriage;
import com.huixh.train.business.domain.DailyTrainCarriageExample;
import com.huixh.train.business.domain.TrainCarriage;
import com.huixh.train.business.enums.SeatColEnum;
import com.huixh.train.business.mapper.DailyTrainCarriageMapper;
import com.huixh.train.business.req.DailyTrainCarriageQueryReq;
import com.huixh.train.business.req.DailyTrainCarriageSaveReq;
import com.huixh.train.business.resp.DailyTrainCarriageQueryResp;
import com.huixh.train.business.service.DailyTrainCarriageService;
import com.huixh.train.business.service.TrainCarriageService;
import com.huixh.train.common.exception.BusinessException;
import com.huixh.train.common.exception.BusinessExceptionEnum;
import com.huixh.train.common.resp.PageResult;
import com.huixh.train.utils.random.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author huixh
 */
@Service
public class DailyTrainCarriageServiceImpl implements DailyTrainCarriageService {

    private final Logger logger = LoggerFactory.getLogger(DailyTrainCarriageServiceImpl.class);
    @Resource
    private DailyTrainCarriageMapper dailyTrainCarriageMapper;
    @Resource
    private TrainCarriageService trainCarriageService;

    @Resource
    private SnowUtil snowUtil;

    @Override
    public void save(DailyTrainCarriageSaveReq dailyTrainCarriageSaveReq) {
        DateTime now = DateTime.now();
        List<SeatColEnum> colEnums = SeatColEnum.getColsByType(dailyTrainCarriageSaveReq.getSeatType());
        if (CollUtil.isEmpty(colEnums)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_SEAT_TYPE_ERROR);
        }
        dailyTrainCarriageSaveReq.setColCount(colEnums.size());
        dailyTrainCarriageSaveReq.setSeatCount(colEnums.size() * dailyTrainCarriageSaveReq.getRowCount());
        DailyTrainCarriage dailyTrainCarriage = BeanUtil.copyProperties(dailyTrainCarriageSaveReq, DailyTrainCarriage.class);
        if (ObjectUtil.isNull(dailyTrainCarriage.getId())) {
            dailyTrainCarriage.setId(snowUtil.getSnowflakeToLong());
            dailyTrainCarriage.setCreateTime(now);
            dailyTrainCarriage.setUpdateTime(now);
            dailyTrainCarriageMapper.insert(dailyTrainCarriage);
        } else {
            dailyTrainCarriage.setUpdateTime(now);
            dailyTrainCarriageMapper.updateByPrimaryKey(dailyTrainCarriage);
        }
    }


    @Override
    public PageResult<List<DailyTrainCarriageQueryResp>> queryList(DailyTrainCarriageQueryReq dailyTrainCarriageQueryReq) {
        DailyTrainCarriageExample dailyTrainCarriageExample = new DailyTrainCarriageExample();
        dailyTrainCarriageExample.setOrderByClause("`date` desc, train_code asc, `index` asc");
        DailyTrainCarriageExample.Criteria criteria = dailyTrainCarriageExample.createCriteria();

        if (StrUtil.isNotBlank(dailyTrainCarriageQueryReq.getTrainCode())) {
            criteria.andTrainCodeEqualTo(dailyTrainCarriageQueryReq.getTrainCode());
        }

        if (ObjectUtil.isNotNull(dailyTrainCarriageQueryReq.getDate())) {
            criteria.andDateEqualTo(dailyTrainCarriageQueryReq.getDate());
        }

        logger.info("查询页码：{}", dailyTrainCarriageQueryReq.getPageNum());
        logger.info("每页条数：{}", dailyTrainCarriageQueryReq.getPageSize());
        PageHelper.startPage(dailyTrainCarriageQueryReq.getPageNum(), dailyTrainCarriageQueryReq.getPageSize());
        List<DailyTrainCarriage> dailyTrainCarriageList = dailyTrainCarriageMapper.selectByExample(dailyTrainCarriageExample);

        PageInfo<DailyTrainCarriage> pageInfo = new PageInfo<>(dailyTrainCarriageList);
        logger.info("总行数：{}", pageInfo.getTotal());
        logger.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainCarriageQueryResp> list = BeanUtil.copyToList(dailyTrainCarriageList, DailyTrainCarriageQueryResp.class);
        return PageResult.success(pageInfo.getTotal(), list);
    }

    @Override
    public void delete(Long id) {
        dailyTrainCarriageMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void genDailyTrainCarriage(String trainCode, Date date) {

        logger.info("生成日期【{}】车次 【{}】 的车厢信息开始", DateUtil.formatDate(date),trainCode);

        DailyTrainCarriageExample dailyTrainCarriageExample = new DailyTrainCarriageExample();
        dailyTrainCarriageExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andDateEqualTo(date);

        dailyTrainCarriageMapper.deleteByExample(dailyTrainCarriageExample);

        List<TrainCarriage> trainCarriages = trainCarriageService.selectByTrainCode(trainCode);

        if (CollUtil.isEmpty(trainCarriages)) {
            logger.info("该车厢没有基础数据，生成车厢信息结束。");
            return;
        }
        List<DailyTrainCarriage> batchList = new ArrayList<>(trainCarriages.size());
        trainCarriages.forEach(trainCarriage -> {
            DateTime now = DateTime.now();
            DailyTrainCarriage dailyTrainCarriage = BeanUtil.copyProperties(trainCarriage, DailyTrainCarriage.class);
            dailyTrainCarriage.setId(snowUtil.getSnowflakeToLong());
            dailyTrainCarriage.setCreateTime(now);
            dailyTrainCarriage.setUpdateTime(now);
            dailyTrainCarriage.setDate(date);
            // dailyTrainCarriageMapper.insert(dailyTrainCarriage);
            batchList.add(dailyTrainCarriage);
        });
        dailyTrainCarriageMapper.insertBatch(batchList);
        logger.info("生成日期【{}】车次 【{}】 的车厢信息结束", DateUtil.formatDate(date),trainCode);
    }

    @Override
    public List<DailyTrainCarriage> selectBySeatType(String seatType, Date date, String trainCode) {
        DailyTrainCarriageExample dailyTrainCarriageExample = new DailyTrainCarriageExample();
        //dailyTrainCarriageExample.setOrderByClause("index asc");
        dailyTrainCarriageExample.createCriteria()
                .andSeatTypeEqualTo(seatType)
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode);
        return dailyTrainCarriageMapper.selectByExample(dailyTrainCarriageExample);
    }
}